<template>
  <div class="main" v-loading="mainLoading">
    <div class="tool-bar">
      <el-button @click="clickRefreshButton">刷新</el-button>
    </div>
    <div class="part-wrapper" v-loading="dnodeLoading">
      <div class="title-wrapper">
        <div class="left-block"></div>
        <div class="title">DNodes</div>
        <div class="right-button">
          <el-button @click="clickAddDnodeButton" icon="Plus" link
            >新增</el-button
          >
        </div>
      </div>
      <div class="content-wrapper">
        <el-table :data="dNodesData">
          <el-table-column
            prop="endpoint"
            label="端点"
            width="220"
            align="center"
          />
          <el-table-column
            prop="vnodes"
            label="虚拟节点"
            width="180"
            align="center"
          />
          <el-table-column
            prop="support_vnodes"
            label="支持虚拟节点数量"
            width="200"
            align="center"
          />
          <el-table-column
            prop="status"
            label="状态"
            width="180"
            align="center"
          />
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column
            prop="operation"
            label="操作"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-button
                icon="delete"
                size="small"
                @click="clickDeleteDNodeButton(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="part-wrapper" v-loading="mnodeLoading">
      <div class="title-wrapper">
        <div class="left-block"></div>
        <div class="title">MNodes</div>
        <div class="right-button">
          <el-button @click="clickAddMorQnodeButton(true)" icon="Plus" link
            >新增</el-button
          >
        </div>
      </div>
      <div class="content-wrapper">
        <el-table :data="mNodesData">
          <el-table-column
            prop="endpoint"
            label="端点"
            width="220"
            align="center"
          />
          <el-table-column
            prop="role"
            label="角色"
            width="380"
            align="center"
          />
          <el-table-column
            prop="status"
            label="状态"
            width="180"
            align="center"
          />
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column
            prop="operation"
            label="操作"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-button
                icon="delete"
                size="small"
                @click="clickDeleteMNodeButton(scope.row, true)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="part-wrapper" v-loading="qnodeLoading">
      <div class="title-wrapper">
        <div class="left-block"></div>
        <div class="title">QNodes</div>
        <div class="right-button">
          <el-button @click="clickAddMorQnodeButton(false)" icon="Plus" link
            >新增</el-button
          >
        </div>
      </div>
      <div class="content-wrapper">
        <el-table :data="qNodesData">
          <el-table-column
            prop="endpoint"
            label="端点"
            width="220"
            align="center"
          />
          <el-table-column label="" width="560" align="center" />
          <el-table-column prop="create_time" label="创建时间" align="center" />
          <el-table-column
            prop="operation"
            label="操作"
            width="120"
            align="center"
          >
            <template #default="scope">
              <el-button
                icon="delete"
                size="small"
                @click="clickDeleteMNodeButton(scope.row, false)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog
      v-model="addDNodeDialogVisiable"
      width="500"
      title="新增数据节点"
      @close="closeAddDnodeDialogFunc"
    >
      <el-form
        ref="addDNodeFormRef"
        label-width="auto"
        :model="addDnodeForm"
        :rules="addDnodeRules"
      >
        <el-form-item label="端点" prop="dnodeEndpoint">
          <el-input v-model.trim="addDnodeForm.dnodeEndpoint"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="clickCancelAddDnodeButton">取消</el-button>
          <el-button type="primary" @click="clickConfirmAddDnodeButton">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="addMNodeDialogVisiable"
      width="500"
      :title="operationType ? '新增管理节点' : '新增计算节点'"
      @close="closeAddMnodeDialogFunc"
    >
      <el-form
        ref="addMNodeFormRef"
        label-width="auto"
        :model="addMnodeForm"
        :rules="addMnodeRules"
      >
        <el-form-item label="DNode" prop="dNodeId">
          <el-select v-model="addMnodeForm.dNodeId" placeholder="DNodes">
            <el-option
              v-for="item in dNodesData"
              :key="item.id"
              :label="item.endpoint"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div>
          <el-button @click="clickCancelAddMnodeButton">取消</el-button>
          <el-button type="primary" @click="clickConfirmAddMnodeButton">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, defineProps } from "vue";

import { getNodesInfo, addNode, deleteNode } from "@/api/index";
import { ElMessage, ElMessageBox } from "element-plus";

const mainLoading = ref(false);
const dnodeLoading = ref(false);
const mnodeLoading = ref(false);
const qnodeLoading = ref(false);

const dNodesData = ref([]);
const mNodesData = ref([]);
const qNodesData = ref([]);
//属性值
const props = defineProps({
	dbInfo:{
		type:Object,
		default:{},
	},
	databaseInfo:{
		type:Array,
		default:[]
	}
})
//数据库信息
const store = {
	info: props.dbInfo,
	databaseInfo: props.databaseInfo
};
//新增删除数据节点相关信息
const addDNodeDialogVisiable = ref(false);
const addDNodeFormRef = ref(null);
const addDnodeForm = ref({
  dnodeEndpoint: "",
});
const addDnodeRules = {
  dnodeEndpoint: [{ required: true, trigger: "blur", message: "请输入端点" }],
};
const clickAddDnodeButton = () => {
  addDNodeDialogVisiable.value = true;
};
const clickCancelAddDnodeButton = () => {
  addDNodeDialogVisiable.value = false;
};
const clickConfirmAddDnodeButton = () => {
  addDNodeFormRef.value.validate((result) => {
    addDNodeDialogVisiable.value = false;
		if (result) {
			mainLoading.value = true;
      let dbConfig = store.info;
      let data = {
        dbConfig,
        type: "dnodes",
        dnodeEndpoint: addDnodeForm.value.dnodeEndpoint,
      };
      addNode(data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("新增成功");
            getNodeInfoByType("dnodes");
          } else {
            ElMessage.error("新增失败:" + res.msg);
          }
					mainLoading.value = false;
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error("新增失败");
					mainLoading.value = false;
        });
    }
  });
};
const closeAddDnodeDialogFunc = () => {
  if (addDNodeFormRef.value) {
    addDNodeFormRef.value.resetFields();
  }
};
const clickDeleteDNodeButton = (rowData) => {
  ElMessageBox.confirm("删除数据节点将删除节点下的所有数据，请谨慎操作！")
    .then(() => {
      let dbConfig = store.info;
      let data = {
        dbConfig,
        type: "dnodes",
        dNodeId: rowData.id,
      };
      mainLoading.value = true;
      deleteNode(data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("删除成功");
            getNodeInfoByType("dnodes");
          } else {
            ElMessage.error("删除失败:" + res.msg);
          }
          mainLoading.value = false;
        })
        .catch((error) => {
          ElMessage.error("删除失败");
          console.error(error);
          mainLoading.value = false;
        });
    })
    .catch((e) => {
      if (e == "cancel") {
        ElMessage.success("取消删除");
      } else {
        ElMessage.error("删除失败");
        console.error(e);
      }
    });
};

//新增删除管理节点或者计算节点相关内容
//true 管理节点 false 计算节点
const operationType = ref(true);
const addMNodeDialogVisiable = ref(false);
const addMNodeFormRef = ref(null);
const addMnodeForm = ref({
  dNodeId: "",
});
const addMnodeRules = {
  dNodeId: [{ required: true, trigger: "change", message: "请选择DNodes" }],
};
const clickAddMorQnodeButton = (type) => {
  operationType.value = type;
  addMNodeDialogVisiable.value = true;
};
const clickCancelAddMnodeButton = () => {
  addMNodeDialogVisiable.value = false;
};
const clickConfirmAddMnodeButton = () => {
  addMNodeFormRef.value.validate((result) => {
		addMNodeDialogVisiable.value = false;
    if (result) {
			mainLoading.value = true;
      let dbConfig = store.info;
      let data = {
        dbConfig,
        type: operationType.value ? "mnodes" : "qnodes",
        dNodeId: addMnodeForm.value.dNodeId,
      };
      addNode(data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("新增成功");
            if (operationType.value) {
              getNodeInfoByType("mnodes");
            } else {
              getNodeInfoByType("qnodes");
            }
          } else {
            ElMessage.error("新增失败:" + res.msg);
          }
					mainLoading.value = false;
        })
        .catch((error) => {
          console.error(error);
          ElMessage.error("新增失败");
					mainLoading.value = false;
        });
    }
  });
};
const closeAddMnodeDialogFunc = () => {
  if (addMNodeFormRef.value) {
    addMNodeFormRef.value.resetFields();
  }
};
const clickDeleteMNodeButton = (rowData, nodeType) => {
  ElMessageBox.confirm("请确认是否删除节点:" + rowData.endpoint)
    .then(() => {
      mainLoading.value = true;
			let dbConfig = store.info;
      let data = {
        dbConfig,
        type: nodeType ? "mnodes" : "qnodes",
        dNodeId: rowData.id,
      };
      deleteNode(data)
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("删除成功");
            if (nodeType) {
              getNodeInfoByType("mnodes");
            } else {
              getNodeInfoByType("qnodes");
            }
          } else {
            ElMessage.error("删除失败:" + res.msg);
          }
					mainLoading.value = false;
        })
        .catch((error) => {
          ElMessage.error("删除失败");
          console.error(error);
					mainLoading.value = false;
        });
    })
    .catch((e) => {
      if (e == "cancel") {
        ElMessage.success("取消删除");
      } else {
        ElMessage.error("删除失败");
        console.error(e);
      }
    });
};

const initData = () => {
  getNodeInfoByType("dnodes");
  getNodeInfoByType("mnodes");
  getNodeInfoByType("qnodes");
};

const clickRefreshButton = () => {
  initData();
};

const getNodeInfoByType = (type) => {
	let loadingObj = null;
  if (type == "dnodes") {
    dnodeLoading.value = true;
		loadingObj = dnodeLoading;
  } else if (type == "mnodes") {
    mnodeLoading.value = true;
		loadingObj = mnodeLoading;
  } else {
    qnodeLoading.value = true;
		loadingObj = qnodeLoading;
  }
  let dbConfig = store.info;
  let data = {
    dbConfig,
    type,
  };
  getNodesInfo(data)
    .then((res) => {
      if (res.code == 200 && res.data) {
        let columnData = res.data[0];
        let data = [];
        for (let i = 1; i < res.data.length; i++) {
          let obj = {};
          for (let j = 0; j < columnData.length; j++) {
            let propNames = columnData[j];
            let value = res.data[i][j];
            obj[propNames] = value;
          }
          data.push(obj);
        }
        if (type == "dnodes") {
          dNodesData.value.length = 0;
          dNodesData.value.push(...data);
        } else if (type == "mnodes") {
          mNodesData.value.length = 0;
          mNodesData.value.push(...data);
        } else {
          qNodesData.value.length = 0;
          qNodesData.value.push(...data);
        }
				loadingObj.value = false;
      } else {
        ElMessage.error(res.msg);
        loadingObj.value = false;
      }
    })
    .catch((e) => {
      console.error(e);
      loadingObj.value = false;
    });
};

onMounted(() => {
  initData();
});
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  height: 100%;
  .tool-bar {
    height: 42px;
  }
  .part-wrapper {
    width: 100%;
    .title-wrapper {
      height: 42px;
      background-color: rgb(235.9, 245.3, 255);
      border-radius: 4px;
      width: 100%;
      position: relative;
      & > div {
        display: table-cell;
        height: 42px;
      }
      .left-block {
        width: 6px;
        background-color: rgb(159.5, 206.5, 255);
        border-top-left-radius: 8px;
        border-bottom-left-radius: 8px;
      }
      .title {
        line-height: 42px;
        padding-left: 8px;
        font-size: 17px;
      }
      .right-button {
        height: 42px;
        position: absolute;
        right: 16px;
        top: 0px;
        line-height: 42px;
      }
    }
    .content-wrapper {
      width: 100%;
      margin: 6px 0;
      height: calc(100% - 42px);
    }
  }
}
</style>
